package com.iflytek.uoamp.agent.core.sender.loggersender;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.iflytek.uoamp.agent.core.AgentCoreMain;
import com.iflytek.uoamp.agent.core.agentclient.async.AsyncWrite;
import com.iflytek.uoamp.agent.core.sender.loggersender.requestobj.AppLogInfo;
import com.iflytek.uoamp.agent.core.sender.loggersender.requestobj.LoggerRequestData;
import com.iflytek.uoamp.agent.core.sender.loggersender.requestobj.ProgramLog;
import com.iflytek.uoamp.agent.core.sender.obj.MsgType;
import com.iflytek.uoamp.agent.core.sender.obj.RequestData;
import com.iflytek.uoamp.agent.core.sender.obj.SysType;

/**
 * @ClassName: LoggerSendMethod
 * @Description: 日志接收转换成对象传递给server
 * @author qinanyuan
 * @date 2017年4月13日 下午4:48:13
 */
public class LoggerSendMethod {

	private AsyncWrite s = new AsyncWrite();

	/**
	 * @Title: sendLogger
	 * @Description: T日志发送方法
	 * @param logger
	 *            void
	 * @date 2017年4月13日 下午4:49:49
	 * @throws
	 */
	public void sendLogger(byte[] logger) {
		RequestData request = new RequestData();
		try {
			LoggerRequestData loggerReq = new LoggerRequestData();
			loggerReq = createLoggerObj(logger);
			request.setSysType(SysType.LOGGER);
			request.setMsgType(MsgType.REQUEST);
			request.setMethod("logger");
			request.setRequestInfo(JSON.toJSONString(loggerReq));
//			Logger.getRootLogger().info("sendLogger请求数据：" + JSON.toJSON(request));
			s.writeAndAsync(AgentCoreMain.getAgentClient().getFuture().channel(), request, 1000);
		} catch (Exception e) {
			Logger.getRootLogger().error("sendLogger fail! The Exception is ：" + e);
		}
	}

	/**
	 * @Title: createLoggerObj
	 * @Description: 构建日志对象
	 * @param logger
	 * @return LoggerRequestData
	 * @date 2017年4月13日 下午4:49:01
	 * @throws
	 */
	public LoggerRequestData createLoggerObj(byte[] logger) {
		LoggerRequestData requestLoggerObj = new LoggerRequestData();
		requestLoggerObj.setId(UUID.randomUUID().toString());
		String loggerString;
		try {
			loggerString = new String(logger, "utf-8");
			if (StringUtils.isNotBlank(loggerString)) {
				// 程序运行日志
				if (loggerString.startsWith("{")) {
					ProgramLog programLog = new ProgramLog();
					AppLogInfo appLogInfo = new AppLogInfo();
					try {
						programLog = JSON.parseObject(loggerString, ProgramLog.class);
						if (StringUtils.isNotBlank(programLog.getAppCode())) {
							requestLoggerObj.setAppCode(programLog.getAppCode());
						}
						
						if (StringUtils.isNotBlank(programLog.getBizName())) {
							requestLoggerObj.setBizName(programLog.getBizName());
						}
						
						if (StringUtils.isNotBlank(programLog.getClassName())) {
							requestLoggerObj.setClasssname(programLog.getClassName());
						}
						if (StringUtils.isNotBlank(programLog.getFlag())) {
							requestLoggerObj.setFlag(programLog.getFlag());
						}
						if (StringUtils.isNotBlank(programLog.getInputArgs())) {
							requestLoggerObj.setInput_para(programLog.getInputArgs());
						}
						if (StringUtils.isNotBlank(programLog.getLocalIp())) {
							requestLoggerObj.setLocalip(programLog.getLocalIp());
						}
						if (StringUtils.isNotBlank(programLog.getMethodName())) {
							requestLoggerObj.setMthodname(programLog.getMethodName());
						}
						if (StringUtils.isNotBlank(programLog.getMsg())) {
							requestLoggerObj.setMsg(programLog.getMsg());
						}
						if (StringUtils.isNotBlank(programLog.getOperateType())) {
							requestLoggerObj.setOperateType(programLog.getOperateType());
						}
						if (StringUtils.isNotBlank(programLog.getOutputArgs())) {
							requestLoggerObj.setOutput_para(programLog.getOutputArgs());
						}
						if (StringUtils.isNotBlank(programLog.getParentId())) {
							requestLoggerObj.setParentid(programLog.getParentId());
						}
						if (StringUtils.isNotBlank(programLog.getRemoteIp())) {
							requestLoggerObj.setRemoteip(programLog.getRemoteIp());
						}
						if (StringUtils.isNotBlank(programLog.getRequri())) {
							requestLoggerObj.setRequri(programLog.getRequri());
						}
						if (StringUtils.isNotBlank(programLog.getSpanId())) {
							requestLoggerObj.setSpanid(programLog.getSpanId());
						}
						if (StringUtils.isNotBlank(programLog.getTraceId())) {
							requestLoggerObj.setTraceid(programLog.getTraceId());
						}
						
						if (StringUtils.isNotBlank(programLog.getWebappName())) {
							requestLoggerObj.setCpid(programLog.getWebappName());
						}
						
						if (StringUtils.isNotBlank(programLog.getEtm() + "")) {
							requestLoggerObj.setEtm(new Date(programLog.getEtm()));
						}
						
						if (StringUtils.isNotBlank(programLog.getSdkLogType().toString())) {
							requestLoggerObj.setLogtype(programLog.getSdkLogType().toString());
						}
						
						if (StringUtils.isNotBlank(programLog.getStm() + "")) {
							requestLoggerObj.setStm(new Date(programLog.getStm()));
						}
						
						if (StringUtils.isNotBlank(programLog.getUtm() + "")) {
							requestLoggerObj.setUtm(programLog.getUtm());
						}
						
						if (StringUtils.isNotBlank(programLog.getWebappPort() + "")) {
							requestLoggerObj.setPort(programLog.getWebappPort() + "");
						}
					} catch (Exception e) {
						appLogInfo = JSON.parseObject(loggerString, AppLogInfo.class);
						if (StringUtils.isNotBlank(appLogInfo.getAppCode())) {
							requestLoggerObj.setAppCode(appLogInfo.getAppCode());
						}
						
						if (StringUtils.isNotBlank(appLogInfo.getAppVersion())) {
							requestLoggerObj.setAppVersion(appLogInfo.getAppVersion());
						}
						
						if (StringUtils.isNotBlank(appLogInfo.getAppDescribe())) {
							requestLoggerObj.setAppDescribe(appLogInfo.getAppDescribe());
						}
						
						if (StringUtils.isNotBlank(appLogInfo.getDepolyIp())) {
							requestLoggerObj.setLocalip(appLogInfo.getDepolyIp());
						}
						
						if(StringUtils.isNotBlank(appLogInfo.getDepolyPort())){
							requestLoggerObj.setPort(appLogInfo.getDepolyPort());
						}
						
						if(StringUtils.isNotBlank(appLogInfo.getVersionInfo())){
							requestLoggerObj.setVersionInfo(appLogInfo.getVersionInfo());
						}
					}


				} else {
					String[] loggers = loggerString.split(" |(\n*\t+)");
//					String[] loggers = loggerString.split(" ");
					// 日志类型
					if (StringUtils.isNotBlank(loggers[0])) {
						requestLoggerObj.setLogtype(loggers[0]);//
					}
					// 本地ip
					if (StringUtils.isNotBlank(loggers[1])) {
						requestLoggerObj.setLocalip(loggers[1].substring(1, loggers[1].length() - 1));
					}
					// 应用名称
					if (StringUtils.isNotBlank(loggers[2])) {
						requestLoggerObj.setAppCode(loggers[2]);
					}
					
					// 组件名称
					if (StringUtils.isNotBlank(loggers[3])) {
						requestLoggerObj.setCpid(loggers[3]);
					}
					
					// 端口
					if (StringUtils.isNotBlank(loggers[4])) {
						requestLoggerObj.setPort(loggers[4].substring(1, loggers[4].length() - 1));
					}
					// Traceid
					if (StringUtils.isNotBlank(loggers[5])) {
						requestLoggerObj.setTraceid(loggers[5]);
					}
					// Parentid
					if (StringUtils.isNotBlank(loggers[6])) {
						requestLoggerObj.setParentid(loggers[6]);
					}
					// Spanid
					if (StringUtils.isNotBlank(loggers[7])) {
						requestLoggerObj.setSpanid(loggers[7]);
					}
					// 远端ip
					if (StringUtils.isNotBlank(loggers[8])) {
						requestLoggerObj.setRemoteip(loggers[8].substring(1, loggers[8].length() - 1));
					}
					// 客户端系统
					if (StringUtils.isNotBlank(loggers[9])) {
						requestLoggerObj.setClientos(loggers[9]);
					}
					// 客户端浏览器
					if (StringUtils.isNotBlank(loggers[10])) {
						requestLoggerObj.setBrowserver(loggers[10]);
					}
					// 开始时间
					if (StringUtils.isNotBlank(loggers[11])) {
						requestLoggerObj.setStm(parseDate(loggers[11]));
					}
					// 请求状态码
					if (StringUtils.isNotBlank(loggers[12])) {
						requestLoggerObj.setRespstatus(loggers[12]);
					}
					// 请求耗时（ms）
					if (StringUtils.isNotBlank(loggers[13])) {
						requestLoggerObj.setUtm(Long.parseLong(loggers[13]));
					}
					// 请求方式（POST/GET）
					if (StringUtils.isNotBlank(loggers[14])) {
						requestLoggerObj.setReq_method(loggers[14]);
					}
					// 请求资源URI
					if (StringUtils.isNotBlank(loggers[15])) {
						requestLoggerObj.setRequri(loggers[15]);
						if (loggers[15].split("\\?").length > 1) {
							Map<String, String> paraMap = new HashMap<String, String>();
							String[] para = (loggers[15].split("\\?"))[1].split("&");
							for (int i = 0; i < para.length; i++) {
								paraMap.put(para[i].split("=")[0], para[i].split("=")[1]);
							}
							// 请求参数
							requestLoggerObj.setReq_para(JSON.toJSONString(paraMap));
						}
					}
					// 请求协议版本
					if (StringUtils.isNotBlank(loggers[16])) {
						requestLoggerObj.setReq_protocol(loggers[16].split("/")[0]);
						if (loggers[16].split("/").length > 1) {
							requestLoggerObj.setPro_version(loggers[16].split("/")[1].trim());
						}
					}

				}

			}

		} catch (UnsupportedEncodingException e) {
			Logger.getRootLogger().error("parse logger fail! The Exception is ：" + e);
		}
		return requestLoggerObj;
	}

	/**
	 * @Title: parseDate
	 * @Description: 时间转换方法
	 * @param dateString
	 * @return Date
	 * @date 2017年4月13日 下午4:49:22
	 * @throws
	 */
	public Date parseDate(String dateString) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");
		Date date = null;
		try {
			date = sdf.parse(dateString);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}
}
